import os
import re
# 设置包含TXT文件的目录
# jpg_directory = r'D:\zxd\lecture\imageProcessing\final\data\pose\train\images'  # 修改为您的TXT文件所在的目录
# txt_directory = r'D:\zxd\lecture\imageProcessing\final\data\pose\train\labels'       # 修改为您的JPG文件所在的目录
jpg_directory = r'data\pose\train\images'  # 修改为您的TXT文件所在的目录
txt_directory = r'data\pose\train\labels'       # 修改为您的JPG文件所在的目录
# jpg_directory = r'data\pose\val\images'  # 修改为您的TXT文件所在的目录
# txt_directory = r'data\pose\val\labels'       # 修改为您的JPG文件所在的目录

# 遍历目录中的所有TXT文件
for filename in os.listdir(txt_directory):
    # 检查文件是否为TXT文件
    if filename.endswith('.txt'):
        # 构建TXT文件的完整路径
        txt_file_path = os.path.join(txt_directory, filename)
        # 使用正则表达式计算文件中单独的“2”的出现次数
        count_2=0
        with open(txt_file_path, 'r') as file:
            content = file.read()
            count_2 = len(re.findall(r'\b2\b', content))
            # 如果单独的“2”的出现次数少于10次，删除TXT文件和同名的JPG文件
        if count_2 < 10:
            os.remove(txt_file_path)
            print(f'Deleted TXT file: {txt_file_path} (Count of standalone "2": {count_2})')
            # 构建同名的JPG文件的完整路径
            jpg_file_path = os.path.join(jpg_directory, filename.replace('.txt', '.jpg'))
            if os.path.exists(jpg_file_path):
                os.remove(jpg_file_path)
                print(f'Deleted JPG file: {jpg_file_path}')